package init.luoyu.easymonitor.zabbix;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import init.luoyu.easymonitor.base.utils.CommonUtil;
import init.luoyu.easymonitor.elastic.ElasticService;
import init.luoyu.easymonitor.server.device.business.service.IDeviceService;
import init.luoyu.easymonitor.server.device.repository.model.CoreDevice;
import init.luoyu.easymonitor.server.item.repository.model.DeviceMonitorItem;
import init.luoyu.easymonitor.server.item.repository.service.IDeviceMonitorItemService;
import init.luoyu.easymonitor.zabbix.server.ZabbixServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>定时获取监控数据定时器</p>
 * @author LuoYu
 * date 2021/5/11
 */
@Component
@Slf4j
public class Scheduler {


    @Resource
    private IDeviceService deviceService;

    @Resource
    private IDeviceMonitorItemService deviceMonitorItemService;

    @Resource
    private ElasticService<MonitorData> elasticService;



    /**
     * 每隔一分钟执行一次
     */
    @Scheduled(fixedRate = 60000)
    public void getMonitorDat() {
        log.info("定时获取监控数据....");
        QueryWrapper<CoreDevice> deviceQuery = new QueryWrapper<>();
        deviceQuery.select("id","hostid").eq("isDeleted",false);
        List<CoreDevice> devices = deviceService.getMapper().selectList(deviceQuery);
        if(CommonUtil.isEmptyCollection(devices)) {
            log.info("未获取到设备信息 ----> 不发送请求");
            return;
        }
        Set<Long> deviceIds = devices.stream().map(CoreDevice::getId).collect(Collectors.toSet());
        QueryWrapper<DeviceMonitorItem> itemQuery = new QueryWrapper<>();
        itemQuery.select("id","deviceId","monitorItemId","itemId").in("deviceId",deviceIds);
        List<DeviceMonitorItem> items = deviceMonitorItemService.list(itemQuery);
        if(CommonUtil.isEmptyCollection(items)) {
            log.info("未配置监控项 ----> 不发送请求");
            return;
        }
        Map<Integer, DeviceMonitorItem> itemMap = items.stream().collect(Collectors.toMap(DeviceMonitorItem::getItemId, Function.identity()));
        List<String> itemIds = items.stream().map(v->String.valueOf(v.getItemId())).collect(Collectors.toList());
        JSONArray jsonArray = ZabbixServer.getMonitorDataByItemIds(itemIds);
        //未获取到数据
        if(CommonUtil.isEmptyCollection(jsonArray)) {
           return;
        }
        List<MonitorData> dataList = Lists.newArrayList();
        for(int i=0;i<jsonArray.size();i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Integer itemId = jsonObject.getInteger("itemid");
            if(itemId == null) {
                continue;
            }
            MonitorData data = new MonitorData();
            data.setClock(jsonObject.getLong("clock"));
            data.setValue(jsonObject.getString("value"));
            data.setItemId(itemId);
            DeviceMonitorItem monitorItem = itemMap.get(itemId);
            if(monitorItem != null) {
                data.setDeviceId(monitorItem.getDeviceId());
                data.setMonitorItemId(monitorItem.getMonitorItemId());
            }
            dataList.add(data);
        }
        elasticService.bulkCreateDocument(ZabbixConstant.ELASTIC_INDEX_NAME,dataList);
    }






}
